package com.wyj.connector;

import com.wyj.server.BaseLiflecycleBean;
import com.wyj.server.Digester;
import com.wyj.server.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.logging.Logger;

/**
 * TODO: 连接，表示tomcat监听的连接信息，包括端口、连接的处理线程数、连接的队列线程数、超时时间等
 *
 * @author wuyijie
 * @date 2021/12/13 22:47
 */
public class Connector extends BaseLiflecycleBean {
    private static final Logger logger = Logger.getLogger(Connector.class.getName());

    private String port;
    private String serviceName;
    private EndPoint endPoint;

    public Connector() {
    }

    public Connector(String port) {
        this.port = port;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public EndPoint getEndPoint() {
        return endPoint;
    }

    public void setEndPoint(EndPoint endPoint) {
        this.endPoint = endPoint;
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    @Override
    public String toString() {
        return "Connector{" +
                "port='" + port + '\'' +
                ", serviceName='" + serviceName + '\'' +
                ", endPoint=" + endPoint +
                '}';
    }

    /**
     * TODO: tcp/ip协议解析内容
     *
     * @author wyj
     * @date 2021/12/14 0:09
     **/
    static class EndPoint {
        private InputStream inputStream;


        public InputStream getInputStream() {
            return inputStream;
        }

        public void setInputStream(InputStream inputStream) {
            this.inputStream = inputStream;
        }
    }


    @Override
    public void init() {
        this.setEndPoint(new EndPoint());

    }

    @Override
    public void start() {
        logger.info("[connector starting : " + this + ", current thread : " + Thread.currentThread().getName() + "]");
        ServerSocket serverSocket = null;
        Socket socket = null;
        try {
            serverSocket = new ServerSocket(Integer.parseInt(this.port));
            while (true) {
                socket = serverSocket.accept();
                //获取输入内容
                InputStream inputStream = socket.getInputStream();
                this.endPoint.setInputStream(inputStream);

                Processor processor = new Processor(socket);
                Service service = Digester.SERVICE_MAP.get(this.serviceName);
                ExecutorService executorService = service.getExecutorService();
                executorService.execute(processor);
                // executorService.shutdown();//gracefully shutdown
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
